package com.omnisyr.textrebuilder;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;

public class TextRebuilder {

	/**
	 * 
	 * Give a folder to this method. </BR>
	 * It will automatically make the files inside be normal styles. </BR>
	 * Always using this after PDFExtractor.py. </BR>
	 * </BR>
	 * For example: </BR>
	 * input: new File("output") </BR>
	 * </BR>
	 * Firstly, texts will be transform to "rebuild.txt" which is readable. </BR>
	 * Then, texts like "Fig. 1. bala-bala" will be extracted to "figure.txt". </BR>
	 * And it will create a "raw" folder inside. </BR>
	 * Images whose title have been found will move to raw folder. </BR>
	 * And a new image called "Fig. x. bala-bala" will be copied to main folder.
	 * </BR>
	 * 
	 * @param folder </BR>
	 *               The files under the folder should looks like: </BR>
	 *               a.jpg</BR>
	 *               b.jpg</BR>
	 *               ...</BR>
	 *               text.md</BR>
	 *               </BR>
	 *               It is the common style exported by PDFExtractor.py. </BR>
	 */
	public static void rebuild(File folder) {

		File rawFolder = new File(folder.getAbsoluteFile() + "/raw");

		if (!rawFolder.exists()) {

			rawFolder.mkdir();

		}

		for (File file : folder.listFiles()) {

			if (!file.getName().endsWith(".md")) {

				continue;

			}

			rebuild(rawFolder, folder, file);

		}

	}

	public static void main(String[] args) {

		File[] folders = new File("output").listFiles();

		for (File folder : folders) {

			rebuild(folder);

		}

	}

	public static void rebuild(File rawFolder, File folder, File text) {

		try {

			Scanner scanner = new Scanner(text, "UTF-8");
			File mainText = new File(text.getPath().replace("text.md", "rebuilded.txt"));
			File figureText = new File(text.getPath().replace("text.md", "figure.txt"));

			if (mainText.exists()) {

				mainText.delete();

			}

			if (figureText.exists()) {

				figureText.delete();

			}

			mainText.createNewFile();
			figureText.createNewFile();

			boolean preCheck = true;
			PrintWriter mainTextWriter = new PrintWriter(new BufferedWriter(new FileWriter(mainText)));
			PrintWriter figureTextWriter = new PrintWriter(new BufferedWriter(new FileWriter(figureText)));

			String cache = "";
			String figurePath = "";
			String figureLine = "";
			String tablePath = "";

			while (scanner.hasNext()) {

				String line = scanner.nextLine();

				if (line.isEmpty()) {

					continue;

				}

				if (preCheck && line.charAt(0) == '#' && line.replaceAll("\\s", "").contains("Introduction")) {

					preCheck = false;

				}

				if (preCheck) {// Ignore lines before introduction.

					continue;

				}

				if (line.replaceAll("\\s", "").contains("References")) {// Ignore lines after references.

					break;

				}

				if (line.length() < 6) {

					continue;

				}

				if (line.charAt(0) == '$') {

					continue;

				}

				if (line.charAt(0) == '#') {// Ignore main titles.

					continue;

				}

				if (line.charAt(0) == '\\') {// Ignore formula.

					continue;

				}

				if (tablePath == null) {

					tablePath = line.substring(4, line.length() - 3);

					new File(tablePath).delete();

					continue;

				}

				if (line.substring(0, 5).equals("Table")) {

					tablePath = null;

					continue;

				}

				if (figureLine == null) {

					if (line.substring(0, 3).equals("Fig")) {

						figureLine = line;

						String index = figureLine.substring(0, figureLine.indexOf('.', 5));

						File from = new File(figurePath);
						File rawFile = new File(rawFolder + "/" + from.getName());
						File to = new File(figurePath.substring(0, figurePath.length() - 68) + index + ".jpg");

						if (!from.exists()) {

							from = rawFile;

						}

						rawFile.createNewFile();
						to.createNewFile();

						Files.copy(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING);
						Files.copy(from.toPath(), rawFile.toPath(), StandardCopyOption.REPLACE_EXISTING);

						from.delete();

						print(figureTextWriter, figureLine);

						continue;

					}

					figureLine = "";

				}

				if (line.charAt(0) == '!') {

					figurePath = line.substring(4, line.length() - 3);
					figureLine = null;

					continue;

				}

				if (hasStrangeStart(line)) {

					cache += line;
					print(mainTextWriter, cache);
					cache = "";

				} else {

					print(mainTextWriter, cache);
					cache = "";
					cache += line;

				}

			}

			scanner.close();
			mainTextWriter.close();
			figureTextWriter.close();

		} catch (Exception ex) {

		}

	}

	public static boolean hasStrangeStart(String str) {

		char ch = str.charAt(0);

		if (ch >= 'a' && ch <= 'z') {

			return true;

		}

		return false;

	}

	public static void print(PrintWriter writer, String cache) {

		if (cache.length() < 1) {

			return;

		}

		cache = cache.trim().replaceAll(" +", " ");

		writer.println(cache);

	}

	public static boolean isNumber(char ch) {

		return ch >= '0' && ch < '9';

	}

}
